angular.module('baisonUser', ['baisonDb', 'baisonService'])
        //用户登录检查
        .factory('UserLoginCheck', ['$location', '$rootScope', function ($location, $rootScope) {
                return function () {
                    if (!$rootScope.user) {
                        $location.path('/login');
                    } else {
                        return;
                    }
                };
            }])
        .factory('PosUser', ['$rootScope', '$q', 'apiService', 'dbSelect', 'dbGetOne', 'dbUpdate', 'dbInsert', 'dbReplace',function ($rootScope, $q, apiService, dbSelect, dbGetOne, dbUpdate, dbInsert,dbReplace) {

                //根据编号查找收银员
                var get_user_by_code = function (code) {
                    var sql = 'select * from PosUser where UserCode = "' + code + '"';
                    return dbGetOne(sql);
                };
                
                //从服务器上查询收银员信息
                var get_user_by_code_from_server = function(code){
                    return apiService('purview/user/get_detail', {'user_code':code});
                };
                //把服务器上查询到的收银员添加到本地
                var add_user_to_local = function(n){
                    var _s = {};
                    var user_data = [];
                    _s.UserCode = n.user_code;
                    _s.role_id = n.role_id;
                    _s.UserName = n.user_name;
                    _s.UserPass = n.password;
                    _s.UserSex = n.sex;
                    _s.ShopCode = n.shop_code;
                    _s.UserTel = (n.tel == undefined) ? '' : n.tel;
                    _s.UserStatus = n.status;
                    _s.UserManage = 1;
                    _s.ShopCodeEx = (n.company_shop_code == undefined) ? '' : n.company_shop_code;

                    _s.roleCode = (n.role_code == undefined) ? '' : n.role_code;
                    _s.maxRebate = (n.max_rebate == undefined) ? '' : n.max_rebate;
                    _s.minRebate = (n.min_rebate == undefined) ? '' : n.min_rebate;
                    _s.signatureCode = (n.signature_code == undefined) ? '' : n.signature_code;
                    _s.maxDiscount = (n.max_discount == undefined) ? '' : n.max_discount;
                    _s.maxPrice = (n.max_price_off == undefined) ? '' : n.max_price_off;
                    _s.minPrice = (n.min_price_off == undefined) ? '' : n.min_price_off;
                    user_data[0] = _s;
                    dbReplace('PosUser', user_data, ['UserCode'], ['role_id', 'UserName', 'UserPass', 'UserSex', 'ShopCode', 'UserTel', 'UserStatus', 'UserManage', 'ShopCodeEx', 'roleCode', 'maxRebate', 'minRebate', 'signatureCode', 'maxDiscount', 'maxPrice', 'minPrice']);
                };

                //根据条件查询收银员列表
                var get_list_by_cond = function (filter) {
                    var where = ' 1=1 ';
                    var sql;
                    $.each(filter, function (index, n) {
                        where = where + ' and ' + index + '="' + n + '"';
                    });
                    sql = 'select * from PosUser where ' + where;
                    return dbSelect('YsPos', sql);
                };
                //获取全部收银员和协作导购员
                var get_list_all = function (filter) {
                    var sql = 'select * from PosUser where UserStatus ="' + filter.UserStatus + '" and ( ShopCode ="' + filter.ShopCode + '" or ShopCodeEx = "' + filter.ShopCode + '")';//or where ShopCodeEx = "' + filter.ShopCode + '"

                    return dbSelect('YsPos', sql);
                };

                //增加收银员到本地
                var add_user_by_code_local = function (data) {
                    data.UserPass = $.md5(data.UserPass);
                    data.role_id = 14;
                    return dbInsert('PosUser', data);
                };

                //增加收银员到服务器
                var add_user_by_code_remote = function (data) {
                    //data.UserPass = $.md5(data.UserPass);
                    var param = {
                        user_code: data.UserCode,
                        user_name: data.UserName,
                        tel: data.UserTel,
                        status: data.UserStatus,
                        password: data.UserPass,
                        shop_code: $rootScope.current_shop.ShopCode,
//                        role_id: data.role_id,
                        role_id: '003',
                        is_clerk: 1
                    };
                    return apiService('purview/user/add', param);
                };
                //增加收银员
                var add_user_by_code = function (data) {
                    return add_user_by_code_remote(data).then(function (success) {
                        if (success.data.status != 1) {
                            var deferred = $q.defer();
                            deferred.reject(success.data.code);
                            return deferred.promise;
                        } else {
                            return add_user_by_code_local(data);
                        }
                    });
                };

                //获取用户角色
                var get_user_role = function () {
                    var sql = 'select * from Pos_user_type';
                    return dbSelect('YsPos', sql);
                }
                //保存收银员信息到本地
                var save_user_by_code_local = function (code, data,type) {

                    var param = JSON.parse(JSON.stringify(data));
                    //modified by lqx maowei on 20170116 解决修改密码后再次登录无法登录的问题，修改面已MD5码加密
                    if (param.UserPass) {
                        param.UserPass = $.md5(param.UserPass);
                    }
                    if(type == 2){ //解绑
                        param.ShopCode = '';
                    }
                    return dbUpdate('PosUser', param, {UserCode: code});
                };

                //保存协作导购员信息到本地
                var save_cooperate_user_by_code_local = function (code, data) {
                    if (data.UserPass) {
                        data.UserPass = $.md5(data.UserPass);
                    }
                    return dbUpdate('PosUser', data, {UserCode: code});
                };
                //保存协作导购员信息到服务器
                var save_cooperate_user_by_code_remote = function (code, data) {
                    var param = {
                        user_code: code,
                        shop_code: $rootScope.current_shop.ShopCode
                    };
                    return apiService('base/shop/submit_cooperate_user', param);
                };

                //绑定协作导购
                var save_cooperate_user_by_code = function (code, data) {
                    if ($rootScope.purview['\/setting\/user2_manage\/cooperate_user_add'].show == 0) {
                        return save_cooperate_user_by_code_local(code, data);
                    } else {
                        return save_cooperate_user_by_code_remote(code, data).then(function (ret) {
                            if (ret.data.status != 1) {
                                var deferred = $q.defer();
                                deferred.reject(ret.data.code);
                                return deferred.promise;
                            } else {
                                return save_cooperate_user_by_code_local(code, data);
                            }
                        });
                    }
                };

                //保存收银员信息到远程服务器
                var save_user_by_code_remote = function (code, data,type, this_data_pass) {
                    var param = {};
                    param.user_code = code;
                    param.user_name = data.UserName;
                    param.tel = data.UserTel;
                    param.status = data.UserStatus;
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    
                    if (type == 2) { //解绑
                        param.shop_code = '';
                        //param.password = pass;
                    }else if(data.UserPass){
						param.password = data.UserPass;
					    //param.password = this_data_pass;
                    }
                    return apiService('purview/user/edit', param);

                };

                //保存收银员信息
                var save_user_by_code = function (code, data,type) {
                    var this_data_pass = data.UserPass;
                    return save_user_by_code_local(code, data, type).then(function (success) {
                        return save_user_by_code_remote(code, data, type, this_data_pass);
                    });
                };

                //根据店铺搜索当前的店员
                var get_user_by_shopCode = function (code) {
                    var UserStatus = 1;
                    var sql = 'select * from PosUser where UserStatus ="' + UserStatus + '" and ShopCode ="' + code + '" or ShopCodeEx = "' + code + '"';
                    return dbSelect('YsPos', sql);
                };

                var get_user_performance = function (data) {
                    var param = {
                        guide_user_code: data.guideCode,
                        shop_code: $rootScope.current_shop.ShopCode,
                        start_sell_time: data.time_start,
                        end_sell_time: data.time_end
                    };

                    return apiService('report/receipt_record/get_receipt_record', param);
                };
                //获取普通导购优惠额度
                var get_user_cut_money = function (code) {
                    var sql = 'select * from PosUser where UserCode = "' + code + '"';
                    return dbSelect('YsPos', sql);
                };
                //获取店长优惠额度
                var get_user_manager = function (ret) {
                    var role_id = '13';
                    var sql = 'select * from PosUser where role_Id = "' + role_id + '" and ShoCode = "' + ret.ShopCode + '" and UserStatus = "' + ret.UserStatus + '"';
                    return dbSelect('YsPos', sql);
                };
                //获取签名码
                var get_sign_by_code = function (code) {
                    var sql = 'select * from PosUser where UserCode = "' + code + '"';
                    return dbSelect('YsPos', sql);
                };
                //修改签名码到服务器
                var change_sign_pass_remote = function (signPass) {
                    var param = {
//                      shop_code:$rootScope.current_shop.ShopCode;
                        user_code: $rootScope.user.UserCode,
                        sign_code: signPass
                    };
                    return apiService('base/shop/submit_manager_sign', param);
                };
                //修改签名码到本地
                var change_sign_pass_local = function (signPass) {
                    $rootScope.user.signatureCode = $.md5(signPass);
                    $rootScope.user.$$hashKey = '';
                    $rootScope.user.active = '';
                    delete($rootScope.user.$$hashKey);
                    delete($rootScope.user.active);
                    dbUpdate('PosUser', $rootScope.user, {UserCode: $rootScope.user.user_code});
                };
                //修改签名码
                var change_sign_pass = function (signPass) {
                    return change_sign_pass_remote(signPass).then(function (ret) {
                        if (ret.data.status != 1) {
                            var deferred = $q.defer();
                            deferred.reject(ret.data.code);
                            return deferred.promise;
                        } else {
                            return change_sign_pass_local(signPass);
                        }
                    });
                };
                //解除绑定到服务器
                var unBind_user_by_code_remote = function (code, data) {
                    var param = {
                        user_code: code,
                        shop_code: $rootScope.current_shop.ShopCode
                    };
                    return apiService('base/shop/relieve_user', param);
                };
                //解除绑定
                var unBind_user_by_code = function (code, data) {
                    return unBind_user_by_code_remote(code, data).then(function (ret) {
                        if (ret.data.status != 1) {
                            var deferred = $q.defer();
                            deferred.reject('TIP_INDEX_NO_INVENTORY');
                            return deferred.promise;
                        } else {
                            return save_user_by_code_local(code, data);
                        }
                    });
                };
                return {
                    get_list_by_cond: get_list_by_cond,
                    get_list_all: get_list_all,
                    save_cooperate_user_by_code: save_cooperate_user_by_code,
                    get_user_by_code: get_user_by_code,
                    save_user_by_code: save_user_by_code,
                    unBind_user_by_code: unBind_user_by_code,
                    save_user_by_code_local: save_user_by_code_local,
                    add_user_by_code: add_user_by_code,
                    get_user_by_shopCode: get_user_by_shopCode,
                    get_user_performance: get_user_performance,
                    get_user_role: get_user_role,
                    get_user_manager: get_user_manager,
                    get_user_cut_money: get_user_cut_money,
                    get_sign_by_code: get_sign_by_code,
                    change_sign_pass: change_sign_pass,
                    get_user_by_code_from_server:get_user_by_code_from_server,
                    add_user_to_local:add_user_to_local
                };
            }])
        //收银员头像设置
        .factory('UserSetPicture', ['$q', function ($q) {

                return function (user_code) {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var himg = "";
                    var user_head = $api.getStorage('user_head') ? $api.getStorage('user_head') : {};
                    if (typeof user_head[user_code] === "undefined") {
                        user_head[user_code] = "./image/head_img_default.png";
                    }
                    baison_app.api.getPicture({
                        sourceType: 'library',
                        encodingType: 'jpg',
                        mediaValue: 'pic',
                        destinationType: 'url',
                        allowEdit: true,
                        quality: 50,
                        targetWidth: 289,
                        targetHeight: 289,
                        saveToPhotoAlbum: false
                    }, function (ret, err) {
                        if (ret) {
                            if (ret.data && ret.data != '') {
                                user_head[user_code] = ret.data;//这个是图片的地址
                            }
                            $api.setStorage('user_head', user_head);
                            deferred.resolve(($api.getStorage('user_head'))[user_code]);
                        } else {
                            deferred.reject(err.msg);
                        }
                    });
                    return promise;
                };


            }])
        //获取获取最新的客户列表
        .factory('CrmCustomerGet', ['apiService', function (apiService) {
                return function () {
                    return apiService('ibeacon/ibeacon/search_by_shop_code', {'shop_code': '001'});
                };
            }])
        //获取店员权限
        .factory('PurviewGet', ['dbSelect', 'apiService', function (dbSelect, apiService) {
                //根据登陆收银员获取权限
                var get_purview_by_user = function (code) {
                    var sql = 'select * from PosPurview where role_id = "' + code + '"';
                    return dbSelect('YsPos', sql);
                };
                //超级管理员登陆密码
                var check_super_manager_password = function () {
                    var ret = 1;
                    return apiService('base/system/check_admin_password', ret);
                };
                return {
                    get_purview_by_user: get_purview_by_user,
                    check_super_manager_password: check_super_manager_password
                };
            }]);